<script setup>
import { useRouter } from "vue-router"; // 导入路由
import { ref, onMounted, watch } from "vue"; // 导入响应式数据和生命周期钩子
import {
  artGetAlgaePhylaAll,
  artGetAlgaeClassAll,
  artPostAlgaeQuery,
  handleLogout,
  artGetStatisticsAll,
  artGetAlgae,
  artDeleteAlgae,
  artPutAlgae,
  artPostPhotoQuery,
  artPostAlgaeAdd,
} from "@/api/algae"; // 导入接口
import { useUserStore } from "@/stores/user"; // 导入用户状态管理
import { ArrowDown, Close } from "@element-plus/icons-vue"; // 导入图标组件

// 跳转路由
const router = useRouter();
//顶部导航栏
//登录成功前后

//用户登录
const userStore = useUserStore(); // 创建 store 实例
const username = userStore.username; // 从 store 中获取用户名

//退出登录
const logout = async () => {
  //  try {
  //   const res = await handleLogout()
  //   console.log(res.data)
  //   // 补充退出逻辑，如清除用户状态、跳转登录页
  //   userStore.removeUsername() // 清除用户名状态
  // } catch (error) {
  //   console.error('退出登录失败:', error.response?.data || error.message)
  // }
  userStore.removeUsername(); // 清除用户名状态
  //刷新页面，清除登录状态
  location.reload();
};

const goToLogin = () => {
  router.push("/login");
};

const gotoAnalyze = () => {
  router.push("/analyze");
};

//藻类内容区
//内容区顶部筛选
// 获取门类
const categories = ref([]);
const getAlgaeListPhyla = async () => {
  try {
    const res = await artGetAlgaePhylaAll();
    categories.value = res.data.data;
    // console.log("门类数据：", categories.value);
  } catch (error) {
    console.error("请求失败：", error);
  }
};

//获取属类
const classes = ref([]);

// 分页渲染
// 定义响应式数据
const selectedCategory = ref("");
const selectedClass = ref(null);
// 构造请求参数（根据接口文档填写必填项）默认状态下
const requestData = ref({
  page: 2, // 分页页码
  pageSize: 16, // 分页大小
  phylaId: "", // 门分类 ID（无过滤时填默认值）
  genusId: "", // 属分类 ID（无过滤时填默认值）
  name: "", // 藻类名称（无过滤时留空）
  latin: "", // 藻类拉丁名（无过滤时留空）
});

const selectedPhyla = ref("");
const selectedPhylaId = ref("");

// 监听 selectedCategory 的变化，根据选择的门类获取对应的属类列表
// 渲染门类筛选后的卡片
const filterSamples = () => {
  const selectedPhyla = selectedCategory.value;
  const selectedPhylaId = categories.value.find(
    (category) => category.phylaName === selectedPhyla
  )?.phylaId;
  //   console.log(selectedPhylaId);
  // 更新请求参数中的门类ID
  // console.log(requestData.value);
  requestData.value.phylaId = selectedPhylaId || "";
  requestData.value.page = 1; // 切换门类时重置到第一页
  selectedClass.value = null; // 清空已选属类
  // console.log(requestData.value);
  getAlgaeList();

  // 添加新的属类筛选监听
  // watch(selectedClass, (newVal) => {
  //   if(newVal) {
  //     console.log("当前选中属类ID:", newVal);
  //     getAlgaeClassDetails();
  //   }})

  // 立即执行异步函数
  const fetchClasses = async () => {
    try {
      if (!selectedPhylaId) return;
      //   console.log('[调试] 请求属类的门类ID:', selectedPhylaId);
      const res = await artGetAlgaeClassAll(selectedPhylaId);
      console.log("[调试] API响应数据:", res.data);
      classes.value = res.data.data.map((item) => ({
        classId: item.genusId,
        className: item.genusName,
        AlgaeId: item.algaeId,
      }));
      console.log("属类数据：", classes.value);
    } catch (error) {
      console.error("请求失败：", error);
    }
  };

  fetchClasses(); // 添加函数调用
};

// 获取分页数据
// 定义响应式数据
const algaeList = ref([]);

// 调用接口获取数据
const getAlgaeList = async () => {
  loading.value = true; // 开始加载
  try {
    const res = await artPostAlgaeQuery(requestData.value);
    // 根据接口实际返回结构处理数据
    algaeList.value = res.data.data;
    // 添加下面两行强制重新渲染
    // algaeList.value = JSON.parse(JSON.stringify(res.data.data)); // 创建新对象触发响应式
    // await nextTick(); // 等待DOM更新
    console.log("藻类列表数据：", algaeList.value);
    // console.log(
    // "藻类列表数据：",
    // JSON.parse(algaeList.value.records[6].algaeImg)
    // );
    // imgUrl.value = JSON.parse(algaeList.value.records[6].algaeImg);
  } catch (error) {
    console.error("请求失败：", error);
  } finally {
    loading.value = false; // 结束加载
  }
};

//搜索 重置
const searchQuery = ref("");
const reset = () => {
  // 清空筛选条件
  selectedCategory.value = "";
  selectedClass.value = null;
  searchQuery.value = "";

  // 重置请求参数
  requestData.value = {
    page: 1,
    pageSize: 16,
    phylaId: "",
    genusId: "",
    name: "",
    latin: "",
  };
  // 清空属类选项
  classes.value = [];
  // 重新获取数据
  getAlgaeList();
};

const onSubmit = () => {
  if (!searchQuery.value) {
    // 空搜索时重置请求参数
    reset();
    return;
  }

  // 使用正则判断是否包含中文
  const hasChinese = /[\u4E00-\u9FA5]/.test(searchQuery.value);

  // 根据输入类型设置对应字段
  requestData.value.name = hasChinese ? searchQuery.value : "";
  requestData.value.page = 1; // 搜索时重置到第一页
  getAlgaeList();
};

//实现分页功能，监听页码变化重新请求数据，更新 algaeList 数据
const handlePageChange = (newPage) => {
  requestData.value.page = newPage;
  getAlgaeList();
};

// 详情页
const Algae = ref([]);
// 添加属类选择监听器
const AlgaeId = ref();
watch(selectedClass, (newVal) => {
  if (newVal && newVal !== AlgaeId.value) {
    // 添加值变化判断
    console.log("已选择属类ID:", newVal);
    AlgaeId.value = newVal;
    getAlgaeClassDetails();
  }
});

//点击卡片详情

const handleCardClick = (algaeId) => {
  if (selectedClass.value !== algaeId) {
    // 添加判断避免重复请求
    selectedClass.value = algaeId;
    console.log("已选择藻类:", algaeId);
  } else {
    getAlgaeClassDetails(); // 相同ID时刷新数据
  }
  router.push({
    path: "/algae/detail",
    query: { algaeId: algaeId },
  });
};

const getAlgaeClassDetails = async () => {
  try {
    const res = await artGetAlgae(AlgaeId.value);
    Algae.value = res.data.data;
    // 确保formData完全更新
    formData.value = {
      ...res.data.data,
      algaeImg: res.data.data.algaeImg,
      algaeId: res.data.data.algaeId,
      genusId: res.data.data.genusId,
      name: res.data.data.name,
      description: res.data.data.description,
      latin: res.data.data.latin,
      memo: res.data.data.memo,
      androidFlag: res.data.data.androidFlag,
    };
    try {
      safeParsedImages.value = JSON.parse(Algae.value.algaeImg) || [];
      mainImageUrl.value =
        safeParsedImages.value[0]?.fileKey.replace(
          "public/common/",
          "algae/public/common/"
        ) || "";
    } catch (e) {
      safeParsedImages.value = [];
      mainImageUrl.value = "";
    }
    console.log("更新后的formData:", formData.value);
  } catch (error) {
    console.error("请求失败：", error);
  }
};

// 详情页图片
// 新增响应式数据
const mainImageUrl = ref("");
const safeParsedImages = ref([]);

// 新增方法
const switchMainImage = (index) => {
  mainImageUrl.value =
    safeParsedImages.value[index]?.fileKey.replace(
      "public/common/",
      "algae/public/common/"
    ) || "";
};

//网站访问数据
const statisticsList = ref([]);
const getStatisticsList = async () => {
  try {
    const res = await artGetStatisticsAll();
    statisticsList.value = res.data.data; // 根据接口实际返回结构处理数据，这里假设数据在 res.data.data 中。如果实际情况不同，需要调整。
    // console.log("统计数据：", statisticsList.value);
  } catch (error) {
    console.error("请求失败：", error);
  }
};

//加载中
const loading = ref(false); // 定义加载状态
const svg = ref(`
        <path class="path" d="
          M 30 15
          L 28 17
          M 25.61 25.61
          A 15 15, 0, 0, 1, 15 30
          A 15 15, 0, 1, 1, 27.99 7.5
          L 15 15
        " style="stroke-width: 4px; fill: rgba(0, 0, 0, 0)"/>
      `);

// 添加

const dialogVisible = ref(false);
const formData = ref({
  algaeId: null,
  genusId: null,
  name: "",
  description: "",
  latin: "",
  memo: "",
  algaeImg: "",
  nameNew: "",
  showFlag: 0,
  deletedFlag: null,
  updateTime: "null",
  createTime: "null",
  androidFlag: 1,
  gatewayFlag: 1,
});

// 删除
const handleDelete = async () => {
  try {
    // 添加确认对话框
    await ElMessageBox.confirm(
      "确定要删除该藻类资料吗？此操作不可撤销！",
      "警告",
      {
        confirmButtonText: "确认删除",
        cancelButtonText: "取消",
        type: "warning",
      }
    );

    // 用户确认后执行删除
    await artDeleteAlgae(AlgaeId.value);
    ElMessage.success("删除成功");
    selectedClass.value = null;
    getAlgaeList();
  } catch (error) {
    // 区分用户取消和真实错误
    if (error !== "cancel") {
      ElMessage.error(
        "删除失败: " + (error.response?.data?.message || error.message)
      );
    }
  }
};

//编辑
const isEditing = ref(false);
const handleSave = async () => {
  try {
    // 确保提交的数据是最新的
    const dataToSubmit = {
      ...formData.value,
      algaeId: AlgaeId.value, // 确保ID正确
    };
    console.log("提交的数据:", dataToSubmit);

    const res = await artPutAlgae(dataToSubmit);
    ElMessage.success("保存成功");
    isEditing.value = false;
    Algae.value = res.data.data;
    getAlgaeClassDetails(); // 刷新详情数据
    getAlgaeList(); // 刷新列表数据
  } catch (error) {
    console.error("保存失败:", error);
    ElMessage.error("保存失败: " + error.message);
  }
};

// 分页查询图片
const showImageDrawer = ref(false);
const imgUrl = ref([]);
const queryData = ref({
  page: 1,
  pageSize: 10,
  fileName: null,
});
const getImgUrl = async (queryData) => {
  try {
    const res = await artPostPhotoQuery(queryData);
    imgUrl.value = res.data.data; // 根据接口实际返回结构处理数据，这里假设数据在 res.data.data 中。如果实际情况不同，需要调整。
    console.log("图片数据：", imgUrl.value);
  } catch (error) {
    console.error("请求失败：", error);
  }
};

const handlePageChange1 = (newPage) => {
  queryData.value.page = newPage; // 更新当前页码
  getImgUrl(queryData.value); // 重新获取数据
};

const handleReset = () => {
  queryData.value.fileName = null;
  // queryData.value.fileType = null;
  getImgUrl(queryData.value);
  handlePageChange1(1);
};
//添加
const formCreate = ref({
  genusI: null,
  name: "",
  latin: "",
  description: "",
  algaeImg: "[]",
  androidFlag: null,
  memo: "",
});

const selectedImages = ref([]); // 新增选中图片数组

// 处理表格行选择
const handleSelectionChange = (selection) => {
  selectedImages.value = selection;
};

// 处理图片确认

const imageTableRef = ref(null); // 新增表格实例引用
const handleImageConfirm = () => {
  console.log(
    "选中的图片路径:",
    selectedImages.value.map((img) =>
      img.fileKey.replace("public/common/", "algae/public/common/")
    )
  );
  showImageDrawer.value = false;
  imageTableRef.value?.clearSelection();
  selectedImages.value = []; // 新增：清空选中状态
};

const handleCreate = async () => {
  try {
    // 调用新建接口（根据实际接口实现）
    const res = await artPostAlgaeAdd(formCreate.value);
    ElMessage.success("新增成功");
    dialogVisible.value = false;

    getAlgaeList(); // 刷新列表数据
  } catch (error) {
    ElMessage.error("新增失败: " + error.message);
  }
};

// 组件挂载时触发请求
onMounted(() => {
  getAlgaeList();
  getAlgaeListPhyla();
  getStatisticsList();
  getImgUrl(queryData.value);
});

// 返回首页
const backToHome = () => {
  router.push("/home");
};

//鼠标拖拽功能
</script>

<template>
  <div class="wrapper">
    <!-- 顶部导航栏 -->
    <div class="header">
      <!-- 左边logo和队名 -->
      <div class="logo-team">
        <img src="../assets/GDOU.png" alt="" /> 广东海洋大学微藻团队
      </div>
      <!-- 右边登录 -->
      <div @click.prevent="goToLogin" class="header-right" v-if="!username">
        登录
      </div>
      <!-- <div class="header-right">{{ username }} <i class="el - icon - arrow - down el - icon--right"></i></div> -->
      <el-dropdown trigger="click" v-if="username">
        <span class="el-dropdown-link" style="color: white; margin-right: 40px">
          {{ username
          }}<el-icon
            class="el-icon--right"
            style="margin-left: 8px; vertical-align: middle"
            ><arrow-down
          /></el-icon>
        </span>
        <template #dropdown>
          <el-dropdown-menu>
            <el-dropdown-item @click="gotoAnalyze">后台管理</el-dropdown-item>
            <el-dropdown-item>上传数据包</el-dropdown-item>
            <el-dropdown-item @click="logout">退出登录</el-dropdown-item>
          </el-dropdown-menu>
        </template>
      </el-dropdown>
    </div>
    <div class="title">水生生物学图谱数据库</div>
  </div>

  <el-row
    class="context-box"
    v-loading.fullscreen.lock="loading"
    element-loading-background="rgba(122, 122, 122, 0.8)"
    element-loading-text="加载中"
    :element-loading-svg="svg"
  >
    <el-col :span="16" :offset="4" class="context">
      <!-- 筛选  添加  搜索  -->
      <el-form class="change" @submit.native.prevent="onSubmit">
        <!-- 门类筛选 -->
        <el-col :span="6">
          <el-form-item label="门类:" v-model="selectedCategory">
            <el-select
              v-model="selectedCategory"
              placeholder="请选择门类"
              @change="filterSamples"
            >
              <el-option
                v-for="(category, index) in categories"
                :key="category.phylald"
                :label="category.phylaName"
                :value="category.phylaName"
              >
                {{ category.phylaName }}
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>

        <!-- 属类筛选 -->
        <el-col :span="6" style="margin-left: 10px; margin-right: 190px">
          <el-form-item
            label="属类:"
            v-model="selectedClass"
            @change="filterSamples"
          >
            <el-select v-model="selectedClass" placeholder="请选择属类">
              <el-option
                v-for="(classItem, index) in classes"
                :key="classItem.classId"
                :label="classItem.className"
                :value="classItem.classId"
              >
                {{ classItem.className }}
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>

        <el-form-item class="add" style="margin-right: 10px" v-if="username">
          <el-button @click="dialogVisible = true">添加</el-button>
        </el-form-item>
        <div v-if="!username" style="width: 69px; color: #000"></div>
        <!-- 搜索与重置按钮 -->
        <el-form-item label="检索:" class="flex items-center">
          <el-input
            type="text"
            v-model="searchQuery"
            placeholder=""
            class="border rounded px-3 py-2 mr-2"
            style="width: 100px"
          />

          <el-button type="primary" @click="reset" style="margin-left: 10px"
            >重置</el-button
          >
          <el-button @click="onSubmit">搜索</el-button>
        </el-form-item>
      </el-form>

      <!-- 展示卡片 -->
      <el-row class="card-wrapper" v-if="!selectedClass">
        <el-col
          :span="6"
          v-for="(item, index) in algaeList.records"
          :key="item.id"
          style="user-select: none"
          @click="handleCardClick(item.algaeId)"
        >
          <div class="card-box">
            <div class="img">
              <img
                :src=" 'http://8.130.47.83:9000/' + `${JSON.parse(item.algaeImg)[0].fileKey.replace(
                  'public/common/',
                  'algae/public/common/'
                )}`"
                alt=""
              />
            </div>
            <div class="desc" style="width: 100%">
              <div class="desc-latin" style="text-align: center">
                {{ item.latin }}
              </div>
              <div style="text-align: center">{{ item.name }}</div>
            </div>
          </div>
        </el-col>
      </el-row>

      <!-- 藻类详情页 -->
      <el-row v-else>
        <el-col :span="18" :offset="3" class="AlgaeAll" v-if="!isEditing">
          <div class="action-bar">
            <el-button @click="selectedClass = null" type="primary"
              >← 返回</el-button
            >
            <div class="action-buttons" v-if="username">
              <el-button type="primary" @click="isEditing = true"
                >编辑</el-button
              >
              <el-button type="primary" @click="handleDelete">删除</el-button>
            </div>
          </div>

          <!-- 内容区域 -->
          <div class="content-wrapper">
            <!-- 左边图片 -->
            <div class="image-section" style="margin-left: 20px">
              <div style="height: 300px">
                <img
                  v-if="mainImageUrl"
                  :src="'http://8.130.47.83:9000/' + mainImageUrl"
                  class="detail-image"
                  style="
                    max-width: 400px;
                    max-height: 300px;
                    width: auto;
                    height: auto;
                    object-fit: contain;
                    margin: 0 auto;
                    display: block;
                  "
                />
              </div>

              <!-- 小图滚动列表 -->

              <div
                class="pictureAll"
                style="
                  display: flex;
                  height: 100px;
                  overflow-x: auto;
                  margin: 10px 0;
                "
              >
                <div
                  v-for="(item, index) in safeParsedImages"
                  :key="index"
                  style="margin: 0 5px; flex-shrink: 0"
                >
                  <img
                    :src="'http://8.130.47.83:9000/' +
                        item.fileKey.replace(
                        'public/common/',
                        'algae/public/common/'
                      )
                    "
                    :style="{
                      width: 'auto',
                      height: '80px',
                      objectFit: 'cover',
                      cursor: 'pointer',
                      opacity:
                        mainImageUrl ===
                        item.fileKey.replace(
                          'public/common/',
                          'algae/public/common/'
                        )
                          ? 1
                          : 0.5,
                      transition: 'opacity 0.3s',
                    }"
                    @click="switchMainImage(index)"
                  />
                </div>
              </div>
            </div>

            <!-- 右边详情 -->
            <div class="info-section">
              <div title="藻类详情" :column="1" border>
                <div class="Algaename">{{ Algae.name || "-" }}</div>

                <div class="Algaelatin">
                  {{ "拉丁文：" + Algae.latin || "-" }}
                </div>

                <div style="font-size: 20px">
                  {{ Algae.description || "暂无详细描述信息" }}
                </div>
              </div>
            </div>
          </div>

          <!-- 编辑 -->
          <div class="bianji"></div>
        </el-col>

        <!-- 编辑表单 -->
        <el-col class="edit-form" :span="18" :offset="3" v-if="isEditing">
          <h2 style="margin-left: 30px">修改藻类信息</h2>
          <el-form :model="formData" label-width="100px">
            <el-form-item label="藻类名称">
              <el-input v-model="formData.name" />
            </el-form-item>
            <el-form-item label="拉丁名">
              <el-input v-model="formData.latin" />
            </el-form-item>
            <el-form-item label="所属门类">
              <el-select
                v-model="formData.genusId"
                placeholder="请选择门类"
                clearable
              >
                <el-option
                  v-for="category in categories"
                  :key="category.phylaId"
                  :label="category.phylaName"
                  :value="category.phylaId"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="描述">
              <el-input
                v-model="formData.description"
                type="textarea"
                :autosize="{ minRows: 3 }"
              />
            </el-form-item>
            <el-form-item label="图片">
              <el-button @click="showImageDrawer = true"
              style="margin-bottom: 20px;"
                >在图片库中选择</el-button
              >
              <div style="width: 100%;display: flex;flex-wrap: wrap;">

                <div class="Imgchange" v-for="(item, index) in JSON.parse(Algae.algaeImg)">
                  <div class="overlay" style="width: 100%;height: 150px;">

                  </div>
                  <img
                
                :src="'http://8.130.47.83:9000/' +
                  item.fileKey.replace('public/common/', 'algae/public/common/')
                "
                alt=""
                class="detailImage"
                />
                <el-input v-model="item.imgRemark"></el-input>
                <!-- <el-check></el-check> -->
                <div>
                  <el-checkbox v-model="formData.androidFlag" label="安卓" name="type"  :true-label="1" :false-label="0" style="width: 50%; margin: 0;"/>
                  <el-checkbox v-model="formData.gatewayFlag" label="PC" name="type"  :true-label="1" :false-label="0" style="width: 50%;margin: 0;"/>
                </div>
                </div>
                
                

              </div>
              
            </el-form-item>
            <el-form-item label="是否同步到安卓端">
              <el-switch
                v-model="formData.androidFlag"
                :active-value="1"
                :inactive-value="0"
                active-text="是"
                inactive-text="否"
              />
            </el-form-item>
            <el-form-item
              label="备忘录"
              type="textarea"
              :autosize="{ minRows: 2 }"
            >
              <el-input v-model="formData.memo" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleSave">确定</el-button>
              <el-button @click="isEditing = false">返回</el-button>
            </el-form-item>
          </el-form>
        </el-col>
      </el-row>
      <!-- 分页  -->
      <div class="pagination" v-if="!selectedClass">
        <el-pagination
          @current-change="handlePageChange"
          :current-page="requestData.page"
          :page-size="requestData.pageSize"
          layout="prev, pager, next"
          :pager-count="5"
          background="#77a5f0"
          :total="algaeList.total"
          sizes="16"
        >
        </el-pagination>
      </div>

      <!-- 版权 -->
      <div class="copyright">
        ©广东海洋大学藻类资源开发与养殖环境生态修复实验室
      </div>
    </el-col>
  </el-row>
  <div class="statistics-container">
    <div class="statistics-item">
      <div class="statistics-title">下载量：</div>
      <div class="statistics-value">
        {{ statisticsList.allDownload }}
      </div>
    </div>
    <div class="statistics-item">
      <div class="statistics-title">今日访问量：</div>
      <div class="statistics-value">
        {{ statisticsList.pvToday }}
      </div>
    </div>
    <div class="statistics-item">
      <div class="statistics-title">今日请求：</div>
      <div class="statistics-value">
        {{ statisticsList.requestToday }}
      </div>
    </div>
    <div class="statistics-item">
      <div class="statistics-title">昨日访问量：</div>
      <div class="statistics-value">
        {{ statisticsList.pvYesterday }}
      </div>
    </div>
    <div class="statistics-item">
      <div class="statistics-title">昨日请求：</div>
      <div class="statistics-value">
        {{ statisticsList.requestYesterday }}
      </div>
    </div>
    <div class="statistics-item">
      <div class="statistics-title">总访问量：</div>
      <div class="statistics-value">
        {{ statisticsList.allPv }}
      </div>
    </div>
    <div class="statistics-item">
      <div class="statistics-title">总请求：</div>
      <div class="statistics-value">
        {{ statisticsList.allRequest }}
      </div>
    </div>
    <div class="download-app">
      <router-link to="/download">下载APP</router-link>
    </div>
  </div>
  <!-- 图片分页 -->
  <div class="image-drawer" :class="{ active: showImageDrawer }">
    <div class="drawer-header">
      <h3>图片库</h3>
      <el-icon class="close-btn" @click="showImageDrawer = false"
        ><Close
      /></el-icon>
    </div>

    <el-form :inline="true" class="search-form">
      <el-form-item label="文件名：">
        <el-input
          v-model="queryData.fileName"
          placeholder="输入文件名"
          clearable
        />
      </el-form-item>
      <el-form-item label="文件类型：">
        <el-select
          v-model="queryData.fileType"
          placeholder="选择文件类型"
          clearable
        >
          <el-option label="JPG" value="jpg" />
          <el-option label="PNG" value="png" />
          <el-option label="GIF" value="gif" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="getImgUrl(queryData)">查询</el-button>
        <el-button @click="handleReset">重置</el-button>
      </el-form-item>
    </el-form>

    <el-table
      ref="imageTableRef"
      :data="imgUrl.records"
      style="width: 100%"
      border="false"
      class="image-table"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" />

      <el-table-column label="图片" width="120">
        <template #default="{ row }">
          <el-image
            :src="
              row.fileKey.replace('public/common/', '/algae/public/common/')
            "
            :preview-src-list="[row.fileKey]"
            fit="cover"
            class="table-image"
          />
        </template>
      </el-table-column>

      <el-table-column prop="fileName" label="图片名称" />

      <el-table-column label="文件大小" width="120">
        <template #default="{ row }">
          {{ (row.fileSize / 1024).toFixed(2) }} KB
        </template>
      </el-table-column>

      <el-table-column prop="fileType" label="文件类型" width="120" />

      <el-table-column label="上传人">
        <template #default>管理员</template>
      </el-table-column>

      <el-table-column label="人员类型" width="120">
        <template #default>员工</template>
      </el-table-column>
      <el-table-column label="操作" width="100">
        <template #default="{ row }">
          <el-button
            type="primary"
            size="small"
            @click="handleDownload(row.fileKey)"
          >
            下载
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="drawer-pagination">
      <el-pagination
        @current-change="handlePageChange1"
        :total="imgUrl.total"
        :current-page="queryData.page"
        :page-size="queryData.pageSize"
        layout="prev, pager, next"
        :pager-count="5"
        background="#77a5f0"
        sizes="16"
        style="display: flex; justify-content: center"
      />
    </div>
    <div
      class="action-buttons"
      style="margin-top: 20px; display: flex; justify-content: end"
    >
      <el-button @click="showImageDrawer = false">取消</el-button>
      <el-button type="primary" @click="handleImageConfirm">确定</el-button>
    </div>
  </div>

  <!-- 添加 -->
  <el-dialog v-model="dialogVisible" title="新增藻类信息" width="50%" center>
    <el-form :model="formCreate" label-width="100px">
      <!-- 复用原有编辑表单结构 -->
      <el-form-item label="藻类名称">
        <el-input v-model="formCreate.name" />
      </el-form-item>
      <el-form-item label="拉丁名">
        <el-input v-model="formCreate.latin" />
      </el-form-item>
      <el-form-item label="所属门类">
        <el-select
          v-model="formCreate.genusId"
          placeholder="请选择门类"
          clearable
        >
          <el-option
            v-for="category in categories"
            :key="category.phylaId"
            :label="category.phylaName"
            :value="category.phylaId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="描述">
        <el-input
          v-model="formCreate.description"
          type="textarea"
          :autosize="{ minRows: 3 }"
        />
      </el-form-item>
      <el-form-item label="图片">
        <el-button @click="showImageDrawer = true">在图片库中选择</el-button>
      </el-form-item>
      <el-form-item label="是否同步到安卓端">
        <el-switch
          v-model="formCreate.androidFlag"
          :active-value="1"
          :inactive-value="0"
          active-text="是"
          inactive-text="否"
        />
      </el-form-item>
      <el-form-item label="备忘录">
        <el-input v-model="formCreate.memo" />
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button @click="dialogVisible = false">取消</el-button>
      <el-button type="primary" @click="handleCreate">确定</el-button>
    </template>
  </el-dialog>
</template>

<style scoped>
/* 顶部导航栏 */

.wrapper {
  width: 100%;
  height: 200px;
  color: white;
  background: url(../assets/homebg.webp) no-repeat;
  background-size: cover;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
  height: 70px;
  background-color: #242f4296;
}

.header .logo-team {
  height: 70px;
  display: flex;
  align-items: center;
  padding-left: 40px;
  font-size: 22px;
}

.header .logo-team img {
  margin-right: 10px;
  width: 50px;
}

.header-right {
  margin-right: 30px;
  cursor: pointer;
}

/* 大标题 */

.title {
  display: flex;
  width: 100%;
  align-items: center;
  justify-content: center;
  margin-top: 20px;
  font-size: 77px;
  font-family: KaiTi;
}

/* home页内容 */

.context-box {
  width: 100%;
  /* height: 800px; */
  min-height: 100vh;
  background-color: #ecf1fb;
}

/* 筛选  添加  搜索  */

.change {
  display: flex;
  margin-top: 20px;
}

.change ::v-deep .add .el-button {
  color: #76a4ee;
  background-color: #e7f0fa;
}

.change ::v-deep .add :hover {
  color: #fff;
  background-color: #75a3ec;
  border-radius: 4px;
  transition-property: all;
  transition-duration: 0.3s;
}

.change ::v-deep .el-form-item__label {
  color: #fff; /* 修改标签颜色 */
}

/* 展示卡片 */

.card-wrapper {
  display: flex;
  flex-wrap: wrap;
  width: 100%;
  margin-top: 13px;
}

.card-wrapper .el-col {
  display: flex;
  justify-content: center;
  margin-bottom: 20px;
}

.card-wrapper .card-box {
  width: 90%;
  height: 250px;
  background-color: #fff;
  border-radius: 15px;
  box-shadow: 0 10px 90px #00000024;
  transition: all 0.5s ease;
  overflow: hidden;
}
/* 鼠标经过 */
.card-wrapper .card-box:hover {
  box-shadow: 0 0px 10px #00000044;
}

/* 卡片图 */
.card-wrapper .card-box .img {
  display: flex;
  justify-content: center;
  height: 200px;
}

.card-wrapper .card-box .img img {
  height: 200px;
}
/* 卡片藻类名字 */

/* 分页 */
.pagination {
  display: flex;
  justify-content: center;
  margin-top: 30px;
  margin-bottom: 20px;
}

.copyright {
  display: flex;
  justify-content: center;
  user-select: none;
}

/* 右侧数据统计框 */
.statistics-container {
  position: fixed;
  top: 250px;
  right: 20px;
  width: 100px;
  background-color: white;
  border-radius: 18px; /* 增加圆角 */
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
  padding: 0; /* 移除内边距 */
  z-index: 100;
  overflow: hidden; /* 确保内容不超出圆角 */
  user-select: none; /* 防止选中文本 */
}

.statistics-item {
  display: flex;
  flex-direction: column; /* 改为纵向排列 */
  align-items: center; /* 居中对齐 */
  padding: 10px 0; /* 添加上下内边距 */
  text-align: center;
  border-bottom: 1px solid #eee; /* 添加底部分隔线 */
}

.statistics-title {
  color: #666;
  font-size: 14px;
  margin-bottom: 5px; /* 标题与数值之间的间距 */
}

.statistics-value {
  color: #333;
  font-size: 16px;
}

.download-app {
  padding: 10px 0;
  text-align: center;
  background-color: white;
}

.download-app a {
  color: #646cff; /* 使用蓝紫色 */
  text-decoration: none;
}

.download-app a:hover {
  opacity: 0.8;
}

/* 修改context-box为相对定位，以便统计框能正确定位 */
.context-box {
  position: relative;
}

/* 藻类详情页 */
.AlgaeAll {
  user-select: none;
  background-color: white;
  /* height: 300px; */
  border-radius: 16px; /* 新增圆角 */
  overflow: hidden; /* 防止内容溢出圆角 */
  margin-top: 40px;
}

/* 顶部 */
.action-bar {
  display: flex;
  justify-content: space-between;
  padding: 10px 35px;
}
/* 中间 */
.content-wrapper {
  display: flex;
  justify-content: space-between;
}

/* 右侧详情 */

.info-section {
  margin-left: 40px;
  margin-right: 20px;
}

.Algaename {
  font-size: 30px;
  font-weight: 700;
  margin-bottom: 5px;
}

.Algaelatin {
  font-size: 24px;
  margin-bottom: 3px;
}

/* 编辑 */
.edit-form {
  user-select: none;
  background-color: white;
  /* height: 300px; */
  border-radius: 16px; /* 新增圆角 */
  overflow: hidden; /* 防止内容溢出圆角 */
  margin-top: 40px;
  padding: 20px 60px;
}

.Imgchange {
  position: relative; /* 添加相对定位 */

  width: 200px;
  /* height: 300px; */
  overflow: hidden;
  margin-right: 30px;
  margin-bottom: 20px;
  border-radius: 10px;
  border: 1px solid #dddddd;
  display: flex;          /* 新增flex布局 */
  flex-direction: column; /* 垂直排列子元素 */
  &:hover .overlay {
    opacity: 1;
  }

}

/* 新增覆盖层样式 */
.Imgchange > div:first-child {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 150px;
  background: rgba(0, 0, 0, 0.5);
  opacity: 0;
  transition: opacity 0.3s ease;
  z-index: 2;
}

.Imgchange img {
  width: 100%;            /* 图片宽度填满容器 */
  height: 150px;          /* 固定图片高度 */
  object-fit: cover;      /* 保持图片比例 */
  flex-shrink: 0;         /* 禁止图片压缩 */
  position: relative; /* 确保图片在覆盖层下方 */
  z-index: 1;
}

.Imgchange .el-input {
  margin-top: 0;
}

/*  */

.pictureAll {
  &::-webkit-scrollbar {
    height: 6px;
    background-color: #f5f5f5;
  }
  &::-webkit-scrollbar-thumb {
    background-color: #409eff;
    border-radius: 4px;
  }
  &::-webkit-scrollbar-track {
    background: #f1f1f1;
  }
}

.image-section {
  min-width: 400px;
}
.detailImage {
  width: 200px;
}
/* 图片分页 */
.image-drawer {
  position: fixed;
  top: 0;
  right: -50%;
  width: 50%;
  height: 100vh;
  background: white;
  box-shadow: -2px 0 12px rgba(0, 0, 0, 0.1);
  transition: right 0.3s ease;
  display: flex;
  flex-direction: column;
  z-index: 3000;

  &.active {
    right: 0;
  }

  .drawer-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 16px;
    border-bottom: 1px solid #eee;

    .close-btn {
      cursor: pointer;
      font-size: 20px;
    }
  }

  .image-grid {
    flex: 1;
    padding: 16px;
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));
    gap: 16px;
    overflow-y: auto;

    .grid-item {
      height: 120px;
      border: 1px solid #eee;
      border-radius: 4px;
      overflow: hidden;

      img {
        width: 100%;
        height: 100%;
        object-fit: cover;
      }
    }
  }

  .drawer-pagination {
    padding: 16px;
    border-top: 1px solid #eee;
  }
}
</style>
